package com.ygqh.baby.controller.admin;

import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.mp.api.NotifyApi;
import com.foxinmy.weixin4j.mp.message.NotifyMessage;
import com.foxinmy.weixin4j.mp.model.User;
import com.foxinmy.weixin4j.payment.mch.Redpacket;
import com.foxinmy.weixin4j.payment.mch.RedpacketRecord;
import com.foxinmy.weixin4j.payment.mch.RedpacketSendResult;
import com.foxinmy.weixin4j.tuple.Text;
import com.ygqh.baby.ao.Message;
import com.ygqh.baby.ao.OrderStatus;
import com.ygqh.baby.ao.QueryInfo;
import com.ygqh.baby.controller.utils.DBHelper;
import com.ygqh.baby.exception.YgException;
import com.ygqh.baby.model.YgUserShareOrderModel;
import com.ygqh.baby.po.*;
import com.ygqh.baby.service.*;
import com.ygqh.baby.service.task.YgRepairDataService;
import com.ygqh.baby.service.wdtqyb.api.WdtQybApi;
import com.ygqh.baby.service.wechat.YgWeChatService;
import com.ygqh.baby.service.wechat.api.YgUserApi;
import com.ygqh.baby.service.wechat.model.Following;
import com.ygqh.baby.shiro.utils.SessionUtil;
import com.ygqh.baby.utils.DateConvertUtils;
import com.ygqh.baby.utils.ThreadPool;
import com.ygqh.baby.utils.YgStringUtils;
import org.apache.log4j.Logger;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Controller
@RequestMapping("/admin/repairData")
public class RepairDataController extends BaseController<Object, java.lang.Long> {
    protected final Logger logger = Logger.getLogger(this.getClass());
    @Autowired
    private YgOrderService ygOrderService;
    @Autowired
    private WdtQybApi wdtQybApi;
    @Autowired
    private YgReturnOrderService ygReturnOrderService;
    @Autowired
    private YgProductService ygProductService;
    @Autowired
    private YgSkuService ygSkuService;
    @Autowired
    private WxMpAuthorityService wxMpAuthorityService;
    @Autowired
    private YgUserService ygUserService;
    @Autowired
    private YgOrderLogService ygOrderLogService;
    @Autowired
    private YgWeChatService ygWeChatService;
    @Autowired
    private YgUserOpenService ygUserOpenService;
    @Autowired
    private BiSkuSaleService biSkuSaleService;
    @Autowired
    private ThreadPool threadPool;
    @Autowired
    private YgCouponService ygCouponService;
    @Autowired
    private YgCouponDetailService ygCouponDetailService;
    @Autowired
    private YgRepairDataService ygRepairDataService;
    @Autowired
    private WxMpMessageService wxMpMessageService;
    @Autowired
    private YgUserBalanceService ygUserBalanceService;

    @RequestMapping("findUserShare")
    @ResponseBody
    public List<YgUserShareOrderModel> findUserShare(QueryInfo queryInfo, String userName) throws YgException {
        YgUser user = ygUserService.findByUserName(userName);
        List<YgUserShareOrderModel> model = ygUserBalanceService.getUserShareOrder(queryInfo, user);
        return model;
    }

    @RequestMapping("findShareOrderInfo")
    @ResponseBody
    public YgUserShareOrderModel findShareOrderInfo(Long orderId) {
        YgUserShareOrderModel model = ygUserBalanceService.findShareOrderInfo(orderId);
        return model;
    }

    @RequestMapping("sendRedpack")
    @ResponseBody
    public RedpacketSendResult sendRedpack(String outTradeNo) throws YgException {
        Redpacket redpacket = new Redpacket(outTradeNo, "test", "oYtnzwNiCCaIyc63_QjzoHuT7Zvs", 1, 1);
        redpacket.setWishing("快来领红包吧！");
        redpacket.setActName("红包测试");
        redpacket.setClientIp("127.0.0.1");
        redpacket.setRemark("haha");
        RedpacketSendResult sendRedpack = ygWeChatService.sendRedpack(redpacket);
        return sendRedpack;
    }

    @RequestMapping("queryRedpack")
    @ResponseBody
    public Message queryRedpack(String outTradeNo) throws WeixinException {
        RedpacketRecord sendRedpack = ygWeChatService.queryRedpack(outTradeNo);
        return Message.success(sendRedpack);
    }

    @RequestMapping("repairBalanceByOrderId")
    @ResponseBody
    public Message repairBalanceByOrderId(Long[] orderIds) throws WeixinException {
        ygRepairDataService.repairBalanceByOrderId(orderIds);
        return Message.success(1);
    }


    @RequestMapping("isSubscribe")
    @ResponseBody
    public Integer isSubscribe(String callback) {

        List<YgUserOpen> list = ygUserOpenService.findScanCountByFromCode(new String[]{"kanjia170830"}, null, null, null);
        // List<String> collect = list.stream().map(u ->
        // u.getOpenId()).collect(Collectors.toList());
        int count = 0;
        for (YgUserOpen u : list) {
            try {
                User user = wxMpAuthorityService.getUserInfo(u.getOpenId());
                System.out.println(user.toString());
                count++;
                System.err.println(count);
            } catch (WeixinException e) {
                e.printStackTrace();
            }
        }

        return count;

    }

    @RequestMapping("buquan")
    @ResponseBody
    public Integer buquan(String orderIds, String callback) {
        Date date = new Date();
        Date endDate = DateConvertUtils.parse("2017-11-11", DateConvertUtils.DATE_FORMAT);
        if (date.before(endDate)) {

            AdminUser user = SessionUtil.getCurrentUser();
            if (orderIds != null) {
                YgCoupon coupon = ygCouponService.findById(225L);

                String[] split = orderIds.split(",");
                List<YgOrder> list = new ArrayList<YgOrder>();
                for (String oid : split) {
                    YgOrder order = ygOrderService.findByOrderId(Long.parseLong(oid));
                    list.add(order);
                }
                ygRepairDataService.sendCoupon1111(list, coupon, endDate, user.getTrueName());
            }
        }
        return 1;

    }

    @RequestMapping("sendTextMsg11buquan")
    @ResponseBody
    public Integer sendTextMsg11buquan(String callback) {

        List<YgUser> list = ygRepairDataService.send11buquan(true);
        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(10);
        for (int i = 0; i < list.size(); i++) {

            final int index = i;
            fixedThreadPool.execute(new Runnable() {

                @Override
                public void run() {
                    String msg = "<a href='http://m.yiigoo.com/static/1510307524.html'>趁老板在家陪娃，双十一200-40元特别券偷偷塞给女王大人们，最夯福利马上直减，还可叠加每满400-50元的满减优惠，不用算了，闭着眼睛买也不亏！另外麻麻剁手委员会福利升级，女王卡神秘上线，免费呆萌入会礼随意选！INS泰国网红玩具plantoys闪团中！双十一进入倒计时，答应我！你别错过！</a>";
                    Text text = new Text(msg);
                    NotifyMessage notifyMessage = new NotifyMessage(list.get(index).getOpenId(), text);
                    NotifyApi notifyAPI = new NotifyApi(wxMpAuthorityService.findTokenHolder());
                    try {
                        notifyAPI.sendNotify(notifyMessage);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }
        return list.size();

    }

    @RequestMapping("sendTemlMsg11buquan")
    @ResponseBody
    public Integer sendTemlMsg11buquan(String callback) {
        List<YgUser> list = new ArrayList<YgUser>();// ygRepairDataService.send11buquan(null);
        YgUser user = new YgUser();
        user.setOpenId("oYtnzwFNcohm5CkQsnAKr9JxrpYA");
        list.add(user);
        String remark = "到我的优惠券看看吧。";
        String link = "/user/list.html";
        String first = "双十一史前最爽折扣，神秘优惠券已经放入您的账户。全场每满400减50，还可叠加双十一特别券，秒杀专场，女王价 <br>" + "多买多赠198元游戏地垫、399元沙发及299元女王卡资格<br>" + "现货新款95鹅绒羽绒服、3M保暖睡袋、亲子装毛衣卫衣，<br>"
                + "今晚8点淘宝直播、现场秒杀、抽奖，大额双十一券疯狂发！<br>" + "到了该拼的时候了，为宝宝买更好的！";
        String start = DateConvertUtils.format(new Date());

        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(10);
        for (int i = 0; i < list.size(); i++) {

            final int index = i;
            fixedThreadPool.execute(new Runnable() {

                @Override
                public void run() {
                    System.out.println(index);
                    YgUser u = list.get(index);
                    String[] keyword = new String[]{u.getUserName(), "有效期 " + start + "至" + "2017-11-13"};
                    wxMpMessageService.sendBindMsg(first, link, remark, u, keyword);
                }
            });
        }

        return list.size();

    }

    @RequestMapping("send11buquan")
    @ResponseBody
    public Integer send11buquan(String callback) {
        List<YgUser> list = ygRepairDataService.send11buquan(null);

        BigDecimal faceValue30 = new BigDecimal("30");
        BigDecimal faceValue40 = new BigDecimal("40");
        Date start = new Date();
        Date end = DateConvertUtils.parse("2017-11-13", DateConvertUtils.DATE_FORMAT);
        List<YgCouponDetail> detailList = new ArrayList<YgCouponDetail>();
        list.forEach(u -> {
            YgCouponDetail detail30 = new YgCouponDetail();
            detail30.setCouponCode(YgStringUtils.getRandomString(12).toUpperCase());
            detail30.setCouponBatchId(227L);
            detail30.setUserId(u.getId());
            detail30.setUserName(u.getUserName());
            detail30.setLeadTime(start);
            detail30.setFaceValue(faceValue30);
            detail30.setStartDate(start);
            detail30.setEndDate(end);
            detail30.setRemark("gh");

            if (u.getIsSubscribe()) {

                YgCouponDetail detail40 = new YgCouponDetail();

                detail40.setCouponCode(YgStringUtils.getRandomString(12).toUpperCase());
                detail40.setCouponBatchId(229L);
                detail40.setUserId(u.getId());
                detail40.setUserName(u.getUserName());
                detail40.setLeadTime(start);
                detail40.setFaceValue(faceValue40);
                detail40.setStartDate(start);
                detail40.setEndDate(end);
                detail40.setRemark("gh");
                detailList.add(detail40);
            }

            detailList.add(detail30);
            detailList.add(detail30);
        });

        return ygCouponDetailService.addCouponDetailBatch(detailList);

    }

    @RequestMapping("goodSale")
    @ResponseBody
    public Integer goodSale(Date startDate, Date endDate) {
        Assert.notNull(startDate);
        Assert.notNull(endDate);
        /*
         * startDate = DateConvertUtils.parse("2016-09-20",
         * DateConvertUtils.DATE_FORMAT); endDate =
         * DateConvertUtils.parse("2017-08-31", DateConvertUtils.DATE_FORMAT);
         */
        long diffDayes = DateConvertUtils.diffDayes(startDate, endDate);

        for (int i = 0; i < diffDayes; i++) {
            final Date runtime = DateConvertUtils.addDay(startDate, i);
            System.err.println(DateConvertUtils.format(runtime));
            threadPool.getExecutorService().execute(new Runnable() {

                @Override
                public void run() {
                    String format = DateConvertUtils.format(runtime);
                    Thread.currentThread().setName(format);
                    System.err.println(Thread.currentThread().getName());
                    List<BiSkuSale> list = biSkuSaleService.statisticalSkuSaleCountOnlyM(null, runtime, DateConvertUtils.addDay(runtime, 1), null);
                    if (list.size() > 0) {

                        System.err.println(list.size());
                    }
                    biSkuSaleService.addBatch(list);

                }
            });

        }
        return 1;

    }

    @RequestMapping("updateSubscribe")
    @ResponseBody
    public String updateSubscribe(String callback) throws WeixinException {
        String nextOpenId = null;
        Boolean falg = true;
        List<String> openIds = new ArrayList<String>();
        int count = 0;
        while (falg) {
            YgUserApi userApi = new YgUserApi(wxMpAuthorityService.findTokenHolder());
            Following following = userApi.getFollowingOpenIds(nextOpenId);
            count += following.getCount();
            if (following.getCount() == 0) {
                break;
            }
            List<String> openIdList = following.getOpenIds();
            for (int i = 0; i < openIdList.size(); i++) {
                openIds.add(openIdList.get(i));
                if (openIds.size() == 500 || i == openIdList.size() - 1) {
                    ygUserService.updateSubscribeStatusBatch(openIds, true);
                    ygOrderLogService.addOrderLog(100L, OrderStatus.TradeClosed, "updateSubscribe", openIds.toString());
                    openIds.clear();
                }
            }

            nextOpenId = following.getNextOpenId();
        }
        System.out.println("count=====================" + count);
        System.out.println("count=====================" + count);
        System.out.println("count=====================" + count);
        return "MESSAGE_SUCCESS";
    }

    @RequestMapping("loadSubscribe")
    @ResponseBody
    public String loadSubscribe(String nextOpenId) throws WeixinException, SQLException {
        Boolean falg = true;
        int count = 0;
        while (falg) {
            YgUserApi userApi = new YgUserApi(wxMpAuthorityService.findTokenHolder());
            Following following = userApi.getFollowingOpenIds(nextOpenId);
            count += following.getCount();
            if (following.getCount() == 0) {
                break;
            }
            List<String> openIdList = following.getOpenIds();
            addWxUser(openIdList);
            nextOpenId = following.getNextOpenId();
        }
        System.out.println("count=====================" + count);
        System.out.println("count=====================" + count);
        System.out.println("count=====================" + count);
        return "MESSAGE_SUCCESS";
    }

    private void addWxUser(List<String> openIds) throws SQLException {
        StringBuilder sb = new StringBuilder();

        String fix = "INSERT INTO wx_user (subscribe,open_id) VALUES";
        DBHelper db = new DBHelper();
        for (int i = 0; i < openIds.size(); i++) {
            String openId = openIds.get(i);
            sb.append("(1,\"" + openId + "\"),");
            if (i != 0 && i % 500 == 0 || i == openIds.size() - 1) {
                sb.deleteCharAt(sb.length() - 1);
                String sql = sb.append(";").toString();
                PreparedStatement statement = null;
                try {
                    sql = fix + sql;
                    System.out.println(sql);
                    statement = db.conn.prepareStatement(sql);
                    statement.executeUpdate();
                } catch (SQLException e) {
                    e.printStackTrace();
                    throw e;
                } finally {
                    if (statement != null) {
                        try {
                            statement.close();
                        } catch (SQLException e) {
                            e.printStackTrace();
                        }
                    }
                }

                sb.delete(0, sb.length());
            }
        }
        db.close();

    }

    public static void main(String[] args) {
        System.out.println(0 % 500);
    }

    /**
     * 得到Excel表中的值
     *
     * @param hssfCell Excel中的每一个格子
     * @return Excel中每一个格子中的值
     */
    @SuppressWarnings("static-access")
    private String getValue(XSSFCell hssfCell) {
        if (hssfCell == null)
            return null;
        if (hssfCell.getCellType() == hssfCell.CELL_TYPE_BOOLEAN) {
            // 返回布尔类型的值
            return String.valueOf(hssfCell.getBooleanCellValue());
        } else if (hssfCell.getCellType() == hssfCell.CELL_TYPE_NUMERIC) {
            DecimalFormat df = new DecimalFormat("0.00");
            String str = df.format(hssfCell.getNumericCellValue());
            // 返回数值类型的值
            return str;
        } else {
            // 返回字符串类型的值
            return String.valueOf(hssfCell.getStringCellValue());
        }
    }


}
